// 简单封装fetch
// 1. 用于get请求
function fetchGet(url, data) {
  if(typeof data == 'object'){
    data = '?'+Object.keys(data).map(key=>`${key}=${data[key]}`).join('&')
  } 
  if(data) url += data
  return fetch(url, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  }).then(responseInterceptor);
}
// 2. 用于post请求
function fetchPost(url, data) {
  return fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  }).then(responseInterceptor);
}
// 3. 用于上传文件
function fetchUpload(url, data) {
  return fetch(url, {
    method: "POST",
    body: data,
  }).then(responseInterceptor);
}

// 响应拦截器
function responseInterceptor(res) {
  return new Promise((resolve, reject) => {
    if (res.status === 200) {
      res.json().then((data) => {
        if (data.code == 200) {
          data.data;
          resolve(data.data);
        }else if(data.code == 666){
          message({ type: "info", message: data.msg });
          resolve(data.data);
        }else {
          reject(res);
          message({ type: "error", message: data.msg });
        }
      });
    } else {
      message({ type: "error", message: "请求失败" });
      reject(res);
    }
  });
}
